package com.jxs.android.sxyw;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jxs.android.sxyw.boot.SelfApplication;
import com.jxs.android.sxyw.data.TaskInfo;
import com.jxs.android.sxyw.weiget.PopMsg;
import com.jxs.android.sxyw.weiget.RefreshListView;
import com.jxs.android.sxyw.weiget.TopBar;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;

/**
 * @Des 巡检列表
 * @Author jiangxs
 * @Des 2012-8-20 下午2:03:35
 */
public class Inspection extends AbstractListActivity {

	private static final int UPDATE_LIST_UI = 0x101;
	private static final int ERROR_MSG = 0x1013;
	private static final int REQUEST_TO_SUBMIT = 0x102;
	private static final int TO_LOGIN = 0x109;

	private String ticket = "";

	private RefreshListView refreshListView;
	private TextView empytText;
	private TaskInfoAdapter taskInfoAdapter;

	private int currentPage = 1; // 最后的可视项索引
	private View loadMoreView;
	private Button loadMoreButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.common_with_list);
		if (null == SelfApplication.getUserInfo() || StringUtils.isEmpety(SelfApplication.getUserInfo().getTicket())) {
			PopMsg.show("登录已过期,请重新登录");
			StartHelper.startActivity(Login.class);
			return;
		}

		loadMoreView = getLayoutInflater().inflate(R.layout.loading_btn, null);
		loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);
		loadMoreButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				loadingData(currentPage, false);
			}
		});

		refreshListView = (RefreshListView) findViewById(R.id.common_listview);
		// refreshListView.addFooterView(loadMoreView);
		empytText = (TextView) findViewById(R.id.null_has_data);
		empytText.setText("暂无巡检任务");
		taskInfoAdapter = new TaskInfoAdapter(Inspection.this);
		refreshListView.setAdapter(taskInfoAdapter);
		ticket = SelfApplication.getUserInfo().getTicket();

		loadingData(currentPage, true);
		refreshListView.setonRefreshListener(new RefreshListView.OnRefreshListener() {
			@Override
			public void onRefresh() {
				loadingData(currentPage, false);
			}
		});
	}

	private void loadingData(int currentPage, boolean isShow) {
		Inspection.this.getWebServiceData(ticket, currentPage, Which.PAGE, isShow, new DataInitListeren() {
			@Override
			public void initData(ProgressDialog progressDialog, boolean isShow) {
				if (isShow) {
					progressDialog.dismiss();
				}
			}
		});
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.setTitle(R.string.xunjian_list_title_label);
		initTopBarReturn(topBar);
		topBar.setLogicBtnText("刷新");
		topBar.setTopBarBtnListern(new TopBar.LogicBtnListern() {
			@Override
			public void onClickLogicBtn() {
				loadingData(currentPage, true);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void paser(int pageNo, SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getPropertySafelyAsString("status");
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getPropertySafelyAsString("message");
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				SoapObject retMsgObject = (SoapObject) soapObject.getProperty("retMsg");
				List<TaskInfo> taskInfos = new ArrayList<TaskInfo>();
				if (null != retMsgObject) {
					for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
						SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);
						TaskInfo taskInfo = new TaskInfo();

						taskInfo.setDeal_user(taskBeanObject.getPropertySafelyAsString("deal_user"));
						taskInfo.setNet_element_name(taskBeanObject.getPropertySafelyAsString("net_element_name"));
						taskInfo.setNet_element_type(taskBeanObject.getPropertySafelyAsString("net_element_type"));
						taskInfo.setPeriod(taskBeanObject.getPropertySafelyAsString("period"));
						taskInfo.setPlan_user(taskBeanObject.getPropertySafelyAsString("plan_user"));
						taskInfo.setSchedule_name(taskBeanObject.getPropertySafelyAsString("schedule_name"));
						taskInfo.setTask_id(taskBeanObject.getPropertySafelyAsString("task_id"));
						taskInfo.setStart_time(taskBeanObject.getPrimitivePropertySafelyAsString("start_time"));
						taskInfo.setEnd_time(taskBeanObject.getPrimitivePropertySafelyAsString("end_time"));

						taskInfos.add(taskInfo);
					}
				}
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				msg.obj = taskInfos;
				handler.sendMessage(msg);
			}
		}
	}

	Handler handler = new Handler() {

		@Override
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_LIST_UI) {

				List<TaskInfo> tems = (List<TaskInfo>) msg.obj;
				empytText.setVisibility(View.GONE);
				taskInfoAdapter.addTaskInfos(tems);
				taskInfoAdapter.notifyDataSetChanged();

				if (currentPage == 1) {
					if (tems.size() < 1) {
						empytText.setVisibility(View.VISIBLE);
						// refreshListView.removeFooterView(loadMoreView);
					}
				}
				refreshListView.onRefreshComplete();
				if (tems.size() < PAGE_SIZE) {
					loadMoreButton.setText("数据已全部获取完毕");
					loadMoreButton.setEnabled(false);
				} else {
					loadMoreButton.setText("查看更多...");
				}
				// currentPage++;
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == TO_LOGIN) {
				PopMsg.show((String) msg.obj);
				StartHelper.startActivity(Login.class);
			}
		}

	};

	private class TaskInfoAdapter extends BaseAdapter {
		private List<TaskInfo> taskInfos = new ArrayList<TaskInfo>();
		private AbstractActivity context;
		private WeakReference<AbstractActivity> revokeActivity;

		private LayoutInflater inflater = null;
		private ViewHolder holder = null;

		public void addTaskInfos(List<TaskInfo> contacts) {
			this.taskInfos.clear();
			this.taskInfos.addAll(contacts);
		}

		public List<TaskInfo> getTaskInfos() {
			return taskInfos;
		}

		public TaskInfoAdapter(AbstractActivity revokeActivity) {
			init(revokeActivity);
		}

		private void init(AbstractActivity revokeActivity) {
			this.revokeActivity = new WeakReference<AbstractActivity>(revokeActivity);
			context = this.revokeActivity.get();
			inflater = (LayoutInflater) revokeActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return taskInfos.size();
		}

		public TaskInfo getItem(int position) {
			return taskInfos.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {
			final TaskInfo taskInfo = taskInfos.get(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.item_icon = (ImageView) convertView.findViewById(R.id.item_icon);
				holder.title_tv = (TextView) convertView.findViewById(R.id.item_title);
				holder.desc_tv = (TextView) convertView.findViewById(R.id.item_des);
				holder.list_menu = (ImageView) convertView.findViewById(R.id.item_arrow);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.item_icon.setImageResource(R.drawable.icon_xunjian_item);
			holder.title_tv.setText(taskInfo.getNet_element_name());
			holder.desc_tv.setText("到期日期 " + taskInfo.getEnd_time());

			OnClickListener onClickListener = new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					onclickView(position, taskInfo);
				}
			};

			holder.list_menu.setOnClickListener(onClickListener);
			convertView.setOnClickListener(onClickListener);
			if (position % 2 == 0) {
				convertView.setBackgroundResource(R.drawable.roundlist_body_gray);
			} else {
				convertView.setBackgroundResource(R.drawable.roundlist_body);
			}
			return convertView;
		}

		private void onclickView(int position, TaskInfo taskInfo) {
			Intent intent = new Intent(context, InspectionSubmit.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("taskInfo", taskInfo);
			bundle.putInt("position", position);
			intent.putExtras(bundle);
			context.startActivityForResult(intent, REQUEST_TO_SUBMIT);
		}

		class ViewHolder {
			ImageView item_icon;// Item中的图片
			TextView title_tv;// Index
			TextView desc_tv;// 昵称
			ImageView list_menu;// 数量
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_TO_SUBMIT) {
			if (resultCode == RESULT_OK) {
				taskInfoAdapter.getTaskInfos().remove(data.getExtras().getInt("position"));
				taskInfoAdapter.notifyDataSetChanged();
			}
		}

	}

	@Override
	public String getMethod() {
		return "getTaskPage";
	}

}
